package com.bac.rentmap.ad.flat.crawler.irrby.proccess;

import java.io.IOException;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import org.springframework.beans.factory.annotation.Required;

import com.bac.rentmap.ad.batch.proccess.BatchProccessor;
import com.bac.rentmap.ad.flat.crawler.FlatCrawledAd;
import com.bac.rentmap.jdo.JdoSupport;

public class IrrByBatchProccessor extends JdoSupport implements BatchProccessor {
	private static final Logger log = Logger
			.getLogger(IrrByBatchProccessor.class.getName());

	private int batchSize;
	private IrrBySecondaryCrawler irrBySecondaryCrawler;

	public int proccess() throws IOException {
		PersistenceManager persistenceManager = getPersistenceManager();
		try {
			Query query = buildQuery(persistenceManager);
			query.setRange(0, batchSize);
			@SuppressWarnings("unchecked")
			List<FlatCrawledAd> flatCrawledAds = (List<FlatCrawledAd>) query
					.execute(Boolean.FALSE);
			for (FlatCrawledAd flatCrawledAd : flatCrawledAds) {
				try {
					irrBySecondaryCrawler.updateFlatCrawledAd(flatCrawledAd);
				} catch (IOException e) {
					log.warning("Problem during retrieving data for "
							+ flatCrawledAd + " from "
							+ flatCrawledAd.getSourceUrl() + " because "
							+ e.getMessage() + ". Deleting it");
					persistenceManager.deletePersistent(flatCrawledAd);
				} catch (NotEnoughDataException e) {
					log.warning("Not enough data for " + flatCrawledAd
							+ " from " + flatCrawledAd.getSourceUrl()
							+ " because " + e.getMessage() + ". Deleting it");
					persistenceManager.deletePersistent(flatCrawledAd);
				}
			}
			return flatCrawledAds.size();
		} finally {
			persistenceManager.close();
		}
	}

	@Required
	public void setBatchSize(int batchSize) {
		this.batchSize = batchSize;
	}

	@Required
	public void setIrrBySecondaryCrawler(
			IrrBySecondaryCrawler irrBySecondaryCrawler) {
		this.irrBySecondaryCrawler = irrBySecondaryCrawler;
	}

	public int getQueueSize() {
		PersistenceManager persistenceManager = getPersistenceManager();
		try {
			Query query = buildQuery(persistenceManager);
			query.setResult("count(this)");
			Object res = query.execute(Boolean.FALSE);
			if(res == null){
			  return 0;
			}
			return ((Number) res).intValue();
		} finally {
			persistenceManager.close();
		}
	}

	public int getBatchSize() {
		return batchSize;
	}

	private Query buildQuery(PersistenceManager persistenceManager) {
		Query query = persistenceManager.newQuery(FlatCrawledAd.class);
		query.setFilter("readyForTransformation == readyForTransformationParam");
		query.declareParameters("Boolean readyForTransformationParam");
		return query;
	}
}
